import React, { useEffect, useState } from 'react'
import { Button, message } from 'antd'
import { useNavigate, useLocation } from 'react-router-dom'
import { queryPictureNameList, queryPictures, handlePictures } from '~/api/upload-item-api'
import { putObject } from '~/components/my-upload'

const userInfo = JSON.parse(localStorage.getItem('u')!) || {}

const selectMap = new Map()

const storePics = new Map()

const ItemPicture = () => {
  const { state }: any = useLocation()
  const navigate = useNavigate()
  const [imgLists, setImgLists] = useState([])
  const [selectImgLists, setSelectImgLists] = useState<any>([])
  const { serialNo } = state

  const handleGetPictureNameList = async () => {
    const { data } = await queryPictureNameList()
    const res = await queryPictures(data)
    setImgLists(res.data)
  }

  //base64转blob
  const dataURLtoFile = (dataurl: string) => {
    const arr = `data:image/png;base64,${dataurl}`.split(',')
    const mime = arr[0].match(/:(.*?);/)![1]
    const bstr = atob(arr[1])
    let n = bstr.length
    const u8arr = new Uint8Array(n)
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n)
    }
    const blob = new File([u8arr], 'file', { type: mime })
    return blob
  }

  const onClickAssociatedPicture = async () => {
    await handlePictures({
      createCompanyCode: userInfo.companyCode,
      createCompanyName: userInfo.companyName,
      createDepartmentCode: userInfo.departmentCode,
      createDepartmentName: userInfo.departmentName,
      createUserName: userInfo.userName,
      createUserNo: userInfo.userNo,
      serialNo,
      storePics: [...storePics.values()]
    })
    message.success('图片关联成功')
  }

  const onClickImg = async (index: number) => {
    const dataurl: any = imgLists[index]
    const files = dataURLtoFile(dataurl)
    selectMap.set(index, !selectMap.get(index))
    const isSelected = selectMap.get(index)
    if (isSelected) {
      const data = await putObject({ files, fileType: 'png', frontend: 'frontendpic' })
      storePics.set(index, {
        name: data.fileName,
        storeId: data.storeId
      })
    }
    setSelectImgLists([...selectImgLists, dataurl])
  }

  console.log('selectImgLists', selectImgLists)

  useEffect(() => {
    handleGetPictureNameList()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])
  return (
    <div>
      <footer>
        <div style={{ marginBottom: 36 }}>
          {imgLists.map((item: any, index: number) => (
            <img
              onClick={() => onClickImg(index)}
              style={{
                width: 300,
                marginLeft: 20,
                cursor: 'pointer',
                border: selectMap.get(index) ? '3px solid red' : 'none'
              }}
              key={index}
              src={`data:image/png;base64,${item}`}
            />
          ))}
        </div>
        <div style={{ marginLeft: 20 }}>
          <Button onClick={onClickAssociatedPicture} type="primary">
            关联图片
          </Button>
          <Button
            style={{ marginLeft: 8 }}
            onClick={() => {
              navigate(-1)
            }}
          >
            返回
          </Button>
        </div>
      </footer>
    </div>
  )
}

export default ItemPicture
